package ai.easy.robot.task

import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.runBlocking
import kotlin.coroutines.experimental.CoroutineContext

/**
 * 子任务内的并行作业
 */
class SubTaskParallelManager(val cctx: CoroutineContext) {

    private val ls = arrayListOf<() -> Boolean>()

    /**
     * 添加并行作业
     */
    fun addJob(job: () -> Boolean) {
        ls.add(job)
    }

    /**
     * 开始并等待所有作业完成
     */
    fun waitAllFinished(): Boolean {
        return runBlocking(cctx) {
            ls.map { my ->
                //创建协程并行运行
                val j = async(cctx) {
                    my()
                }
                j
            }.all {
                it.await()
            }
        }
    }

    /**
     * 延时
     */
    fun delayMs(ms: Int) {
        runBlocking(cctx) {
            delay(ms.toLong())
        }
    }


}